'''
Created on 2010/08/11

@author: yukiyonezawa
'''
from pyrfid.asn1.Encoder import Encoder
from pyrfid.Util.Util import Util
class SecondaryID(object):
    #next implements
    
    __SECONDARY_EBV = 4        
    __SECONDARY_LIST = list()
    
    def __init__(self):
        self.__SECONDARY_LIST = list()
        pass
        
    def build(self, defined_packed_objects, changed_order_add_data_set_list):        
        
        #extract 391%x30~90 from defined_packed_objects
        IDInfos = defined_packed_objects.getIDInfo()
        secondary_ID_list = list()
        for info in IDInfos:
            if "%" in info.getOIDString(False):
                OIDList = list()
                for OIDString in info.getOIDString():
                    OIDList.append({"OIDString":OIDString, "OID":Encoder.oidEncode(defined_packed_objects.getKRootOID() +" " + OIDString)})
                
                for OID in OIDList:
                    for data_set in changed_order_add_data_set_list:
                        if OID["OID"] == data_set.OBJECT_IDENTIFIER:
                            #extract ID
                            index = info.getOIDString(False).index("%")                            
                            
                            secondary_ID_list.append(OID["OIDString"][index:])
                            self.addPrefixAndSecondaryList(OID["OIDString"][:index], OID["OIDString"][index:])
            
    def addPrefixAndSecondaryList(self, prefix, secondary):        
        self.__SECONDARY_LIST.append({"PREFIX":str(prefix), "SECONDARY":str(secondary)})
    
    @classmethod
    def analyzeSecondaryId(cls, all_data_bit, included_idInfo):
        
        
        
        secondary_id_list = list()
        for idInfo in included_idInfo:
            if "%" in idInfo.getOIDString(False):
                secondary_id_list.append(idInfo)
                
        secondary= SecondaryID()        
        for idInfo in secondary_id_list:
            secondary_id = Util.convertExtensibleBitVertorToInt(all_data_bit, cls.__SECONDARY_EBV)
            all_data_bit = all_data_bit[len(Util.convertExtensibleBitVectorToBit(secondary_id, cls.__SECONDARY_EBV)):]
            index = idInfo.getOIDString(False).index("%")
            prefix = idInfo.getOIDString(False)[:index]        
            secondary.addPrefixAndSecondaryList(prefix, secondary_id)        
        
        return (secondary, all_data_bit)
        
    def getSecondaryIdByIndex(self, index):
        return self.__SECONDARY_LIST[index]
    
    def getBit(self):
        print self.__SECONDARY_LIST
        return_bit = ""
        for ID in self.__SECONDARY_LIST:
            return_bit += Util.convertExtensibleBitVectorToBit(int(ID["SECONDARY"]), self.__SECONDARY_EBV)
        return return_bit
    